import asyncio
import json
from playwright.async_api import async_playwright

async def fetch_top_charts():
    async with async_playwright() as p:
        # 启动浏览器
        browser = await p.chromium.launch(headless=False)

        # 加载之前保存的登录态
        context = await browser.new_context(storage_state="storage.json")

        # ✅ 用 request API 请求排行榜接口
        # 游戏','社交','娱乐','效率','购物','教育','健康健身','商务','生活','金融','旅行'
        api_url = "https://app.sensortower-china.com/api/ios/category_rankings?offset=0&limit=100&category=6003&country=US&date=2025-09-09&device=iphone"
        response = await context.request.get(api_url)

        if response.ok:
            raw_data = await response.json()
            print("✅ API 返回成功，正在处理数据...")

            # 假设返回结构类似 { "data": { "free": [...] } }
            free_list = raw_data.get("data", {}).get("free", [])
            for item in free_list:
                item["category"] = "旅行"
                item["google_play_url "] = ""
                item["app_store_url "] = ""

            # 保存修改后的 JSON
            with open("allsensortower旅行.json", "w", encoding="utf-8") as f:
                json.dump(raw_data, f, ensure_ascii=False, indent=2)

            print("📁 已保存为 allsensortower金融.json，且每个对象都加了 country=美国")
        else:
            print("❌ 请求失败，状态码:", response.status)

        await browser.close()

asyncio.run(fetch_top_charts())
